package com.echo.blog.business.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.echo.blog.business.blog.dao.BlogTagRelationMapper;
import com.echo.blog.business.blog.model.BlogTag;
import com.echo.blog.business.blog.model.BlogTagRelation;
import com.echo.blog.business.blog.service.IBlogTagRelationService;
import com.echo.blog.business.sys.model.SysUser;
import com.echo.model.common.RequestHolder;
import com.echo.model.constant.ConstantUtils;
import com.echo.model.context.LoginUser;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chentl123
 * @since 2019-09-26
 */
@Service
public class BlogTagRelationServiceImpl extends ServiceImpl<BlogTagRelationMapper, BlogTagRelation> implements IBlogTagRelationService {
    @Override
    public void deleteByBlogId(Integer blogId) {
        //先删除关联  然后插入博客和标签的关联关系
        QueryWrapper<BlogTagRelation> wrapper = new QueryWrapper<>();
        wrapper.eq(ConstantUtils.Public.BLOG_ID, blogId);
        this.baseMapper.delete(wrapper);
    }


    @Override
    public void rebuildBlogTagRelation(List<BlogTag> tags, Integer blogId) {

        LoginUser loginUser = RequestHolder.getCurrentUser();
        Integer userId = loginUser.getId();
        //1 删除关联
        deleteByBlogId(blogId);
        List<BlogTagRelation> relationsList = new ArrayList<>();
        //2 重建关联
        for (BlogTag tag : tags) {
            BlogTagRelation relation = new BlogTagRelation();
            relation.setBlogId(blogId);
            relation.setTagId(tag.getId());
            relation.setCreateby(userId);
            relation.setUpdateby(userId);
            relationsList.add(relation);
        }
        this.saveBatch(relationsList);
    }
}
